package de.backtomedieval.activities.gamemenu;

import java.util.ArrayList;


import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.content.res.Resources;
import android.graphics.drawable.Drawable;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.Handler;
import android.text.Html;
import android.text.Html.ImageGetter;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.WindowManager;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ArrayAdapter;
import android.widget.BaseAdapter;
import android.widget.GridView;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.RelativeLayout;
import android.widget.TextView;
import de.backtomedieval.R;
import de.backtomedieval.activities.TopBar;
import de.backtomedieval.buildings.*;
import de.backtomedieval.main.Game;
import de.backtomedieval.research.AbstractResearch;
import de.backtomedieval.game.Helper;

public class Researchmenu extends Activity {
	
	private ListView lv1;
	private AbstractResearch toResearch = null;
	private ArrayList<AbstractResearch> m_research;
    private ResearchAdapter m_researchadapter;
	private Handler mHandler = new Handler();
	private GridView grid_main;
	private TextView tv_researchinfo;
	private LinearLayout layoutChoose;
	private RelativeLayout layoutInfo;
	private int refresh = Game.getRefreshrate();
	private TopBar topbar;
	
	@Override
	public void onCreate(Bundle savedInstanceState)	{
		super.onCreate(savedInstanceState);
		getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN, WindowManager.LayoutParams.FLAG_FULLSCREEN );
		setContentView(R.layout.researchmenu);
		
		
		tv_researchinfo = (TextView) findViewById(R.id.researchmenu_researchinfo);
		layoutChoose = (LinearLayout)findViewById(R.id.LayoutResearchChoose);
		layoutInfo = (RelativeLayout)findViewById(R.id.LayoutResearchInfo);
		
		topbar = new TopBar(this);
		topbar.setTitle(Game.getGame().getcCity().getName() + ": " + getString(R.string.research));
		
		Game.setLastActivity(this);
		lv1=(ListView)findViewById(R.id.ListViewResearch);
        m_research = Game.getGame().getPlayer().getTechnology().getResearch();
        this.m_researchadapter = new ResearchAdapter(this, R.layout.row, m_research);
       lv1.setAdapter(this.m_researchadapter);
       ArrayList<AbstractResearch> u = new ArrayList<AbstractResearch>();
       for (int i=0; i<u.size(); i++) {
    	   m_researchadapter.add(u.get(i));
       }
       m_researchadapter.notifyDataSetChanged();
      
        lv1.setTextFilterEnabled(true);
 
        lv1.setOnItemClickListener(new OnItemClickListener() {
            public void onItemClick(AdapterView<?> parent, View view,
                    int position, long id) {
            	onResearchListChoose(position);
            }
        });
                        
		grid_main = (GridView)findViewById(R.id.GridViewMenu);
		grid_main.setAdapter(new ImageAdapter(this));
        grid_main.setOnItemClickListener(new OnItemClickListener() {
            public void onItemClick(AdapterView<?> parent, View view,
                    int position, long id) {
            	onResearchInfoMenuChoose(position);
            }
        });

	}
	
	protected void onResearchInfoMenuChoose(int position) {
		if (toResearch != null) {
			if (position==0) {
				onButtonResearch();
			}
		}
	}
	
	@Override
	public void onBackPressed() {
		RelativeLayout l1 =(RelativeLayout)findViewById(R.id.LayoutResearchInfo);
    	int vis = l1.getVisibility();
		if (vis == 0) {
			switchToResearchList();
		} else {
			mHandler.removeCallbacks(mUpdateTask);
			Intent changeToIntent = new Intent(this,Gamemenu.class);
			startActivity(changeToIntent);

			this.finish();
		}
		
		return;
	}

	protected void onButtonResearch() {
		if (toResearch != null) {
			Academy a = Game.getGame().getcCity().getAcademy();
			if (!a.isBuilded()) {
				Game.showPopup(this, Game.getString(R.string.youneedaacademy));
				return;
			}
			if (a.getToResearch()==null) {
				a.setToResearch(toResearch);
			} else {
				//FEHLER!
				Game.showPopup(this, Game.getString(R.string.researchalready));
			}
			
		}
		switchToResearchList();
		m_researchadapter.notifyDataSetChanged();
	}

	private void switchToResearchList() {
		layoutInfo.setVisibility(8);
    	layoutChoose.setVisibility(0);
	}
	
	private void switchToResearchInfo() {
		layoutChoose.setVisibility(8);
    	layoutInfo.setVisibility(0);
	}
	
	private class CreateResearchInfoTask extends AsyncTask<Void, Void, String> {
	    /** The system calls this to perform work in a worker thread and
	      * delivers it the parameters given to AsyncTask.execute() */
		@Override
		protected String doInBackground(Void... params) {
			 return buildResearchInfo();
		}
	    /** The system calls this to perform work in the UI thread and delivers
	      * the result from doInBackground() */
	    protected void onPostExecute(String result) {
	    	Log.v("Update", "Researchinfo");
	    	tv_researchinfo.setText(Html.fromHtml(result, imgGetter, null));
	    }
	}

	public String buildResearchInfo() {
    	String info ="<Big><b>"+toResearch.getName()+"</b></Big> - ";
    	
    	
    	Academy a = Game.getGame().getcCity().getAcademy();
    	if (!toResearch.isResearched()) {
			if (toResearch.getResearchPoints()==0) {
				info += "" + getString(R.string.notresearchedyet) +"<br><br>";
				if (a!=null && a.isBuilded()) info += getString(R.string.researchtime) + ": " + "<img src=\"round\">"+  a.getResearchTime(toResearch) + "<br>";
				info += toResearch.getResearchInfo(toResearch.getLevel()+1)+"<br>";
			} else {
				info += "" + getString(R.string.researchinprogress)+"<br><br>";
				info += toResearch.getResearchInfo(toResearch.getLevel()+1)+"<br>";
			}
		} else {
			info += "<b>Level " + toResearch.getLevel() +"</b><br><br>";
			info += "<b>" + getString(R.string.currentlevel) + "</b>:<br>";
			info += toResearch.getResearchInfo(toResearch.getLevel())+"<br>";
			info +=  "<br><b>" + getString(R.string.nextlevel) +  "</b>:<br>";
			
			if (a!=null && a.isBuilded()) info += getString(R.string.researchtime) + ": " + "<img src=\"round\">"+  a.getResearchTime(toResearch) + "<br>";
			info += toResearch.getResearchInfo(toResearch.getLevel()+1)+"<br>";
			if (toResearch.getResearchPoints() != 0) {
				info = info +"<br><br>" + getString(R.string.researchtolevel1) +" "+ (toResearch.getLevel()+1) + " "+ getString(R.string.researchtolevel2) +  ".";
			}
		}
    	
		return info;
	}
		
	protected void onResearchListChoose(int position) {
		if (position!=-1)
			toResearch = m_researchadapter.getItem(position);
		if (toResearch != null) {
			if (position!=-1) tv_researchinfo.setText("");
			if (position!=-1) switchToResearchInfo();
			new CreateResearchInfoTask().execute();
			grid_main.setAdapter(new ImageAdapter(this));
			/*if (position!=-1 || lastState != (toResearch.getBuildCountdown()==0)) {
				grid_main.setAdapter(new ImageAdapter(this));
			}*/
		} else {
		}		
	}
	
   ImageGetter imgGetter = new Html.ImageGetter() {
        @Override
        public Drawable getDrawable(String source) {
              Resources res = Researchmenu.this.getResources();
              Drawable drawable = res.getDrawable(Helper.getImageFromString(source));
              drawable.setBounds(0, 0, drawable.getIntrinsicWidth()/3, drawable.getIntrinsicHeight()/3);
              return drawable;
        }
    };

	private Runnable mUpdateTask = new Runnable() {
		   public void run() {
		       if (layoutChoose.getVisibility()==0) {
		    	   m_researchadapter.notifyDataSetChanged();
		    	   Log.v("Update", "Researchchooselist");
		       } else {
		    	   onResearchListChoose(-1);
		    	   Log.v("Update", "Research Info");
		       }
		       Log.v("Update", "Cityinfo");
		       topbar.refreshCityInfo();
		       mHandler.postDelayed(this,refresh);
		   }
	};
	
	
	private class ResearchAdapter extends ArrayAdapter<AbstractResearch> {

	    private ArrayList<AbstractResearch> items;

	    public ResearchAdapter(Context context, int textViewResourceId, ArrayList<AbstractResearch> items) {
	            super(context, textViewResourceId, items);
	            this.items = items;
	    }

	    @Override
	    public View getView(int position, View convertView, ViewGroup parent) {
	            View v = convertView;
	            if (v == null) {
	                LayoutInflater vi = (LayoutInflater)getSystemService(Context.LAYOUT_INFLATER_SERVICE);
	                v = vi.inflate(R.layout.row, null);
	            }
	            AbstractResearch o = items.get(position);
	            if (o != null) {
	                    TextView tt = (TextView) v.findViewById(R.id.toptext);
	                    TextView bt = (TextView) v.findViewById(R.id.bottomtext);
	                    ImageView icon=(ImageView)v.findViewById(R.id.icon);
	                     icon.setImageResource(o.getImage());
	                    if (tt != null) {
	                          tt.setText(o.getName());
	                    }
	                    if(bt != null){
	                    	
	                    	if (o.isResearched()) {
	                    		if (o.getResearchPoints() == 0 ) {
	                    			bt.setText("Level "+ o.getLevel());
	                    		} else {
	                    			bt.setText("Level "+ o.getLevel() + " | " +  getString(R.string.researching) +"... "+ o.getResearchPercent());
	                    		}
	                    	} else {
	                    		if (o.getResearchPoints() == 0 ) {
	                    			bt.setText(getString(R.string.notresearchedyet));
	                    		} else {
	                    			bt.setText(getString(R.string.researchinprogress) + "... " +o.getResearchPercent());
	                    		}
	                    	}
	                   
	                    }
	                    
	                    
	                    
	            }
	            return v;
	    }
	}
	
	
	public class ImageAdapter extends BaseAdapter{
		Context mContext;
		public static final int ACTIVITY_CREATE = 10;
		public ImageAdapter(Context c){
			mContext = c;
		}

		public int getCount() {
			return 1;
		}


		public View getView(int position, View convertView, ViewGroup parent) {
			View v;
			if(convertView==null){
				LayoutInflater li = getLayoutInflater();
				v = li.inflate(R.layout.gridiconlarge, null);
				TextView tv = (TextView)v.findViewById(R.id.icon_text);
				ImageView iv = (ImageView)v.findViewById(R.id.icon_image);
				//inearLayout ll = (LinearLayout)v.findViewById(R.id.gridicon);
				if (toResearch!=null) {
					if(position ==0) {
						tv.setText(R.string.research);
						iv.setImageResource(R.drawable.research);
					}
				}

			}
			else{
				v = convertView;
			}
			return v;
		}
		
		
		
		public Object getItem(int position) {
			return null;
		}
		
		public long getItemId(int position) {
			return 0;
		}
	}

	
	@Override
	public void onResume(){
	   super.onResume();
       mHandler.removeCallbacks(mUpdateTask);
       mHandler.postDelayed(mUpdateTask, 100);
	   Game.setLastActivity(this);
	}

	@Override
	public void onStop() {
		super.onStop();
	}

	@Override
	public void onPause(){
	   super.onPause();
	   mHandler.removeCallbacks(mUpdateTask);
	}
	
}



